package com.candy.candysocket.mq;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/8/22 16:04
 * @Description 生产者
 */
@Slf4j
@Component
public class ProducerExampleBoot implements CommandLineRunner {

    @Resource(name = "extRocketMQTemplate")
    RocketMQTemplate rocketMQTemplate;

    @SneakyThrows
    public void sendMsg(String topic, String msg) {

        log.info("topic:{},msg:{}", topic, msg);
//        SendResult sendResult = rocketMQTemplate.syncSend(topic, msg);

//        SendResult sendResult = rocketMQTemplate.syncSendDelayTimeSeconds(topic, msg, 10);
        // TODO 各种消息类型玩玩

        Message message = new Message(topic, (msg + 1).getBytes(StandardCharsets.UTF_8));
        // 延迟 10s 后投递
        message.setDelayTimeSec(10);
        // 延迟 10000ms 后投递
        // message.setDelayTimeMs(10_000L);
        // 定时投递，定时时间为当前时间 + 10000ms
        // message.setDeliverTimeMs(System.currentTimeMillis() + 10_000L);
        // 发送消息
        SendResult sendResult = rocketMQTemplate.getProducer().send(message);
        log.info("msg:{},result:{}", msg, JSONObject.toJSONString(sendResult));
/*        Message<String> msgs = MessageBuilder.withPayload("我是一个boot消息")
                //设置消息KEYS,一般是数据的唯一ID,主要用于在仪表盘中方便搜索
                .setHeader("KEYS", System.currentTimeMillis())
                .build();

        //给消息打上射手的标签。主题+tag，中间用“:”分隔,主要是用于消息的过滤，比如说在消费的时候，只消费ESS标签下的消息
        String topic = "myGroup";
        rocketMQTemplate.sendOneWay(topic, msgs);*/

        // rocketMQTemplate.convertAndSend("myGroup", "msgs11111111111");
    }

    // 遇到问题
// https://blog.csdn.net/zhangzengxiu/article/details/119062079
    @Override
    public void run(String... args) throws Exception {
//        broadcastMsg(null, null);
    }

}
